import {
  AccountApi,
  deleteAccount,
  fetchAccountRoleList,
  insertAccount,
  resetAccountPassword,
  updateAccount,
  updateAccountRole,
} from '@/api/userCenter/authority/account'
import {
  CommonUserInfo,
  InsertAccountReq,
  ModifyAccountReq,
  ModifyAccountRoleReq,
} from '@/api/userCenter/authority/model/accountModel'
import { fetchRoleList, RolesApi } from '@/api/userCenter/authority/roles'
import { useStore } from '@/store'
import { computed, onMounted, reactive, watchEffect } from '@vue/runtime-core'
import { message } from 'ant-design-vue'
import { cloneDeep, isArray } from 'lodash-es'
import { AccountDialogFormState, DialogState } from '../types'

const useModifyUser = (searchApi: () => Promise<void>) => {
  const store = useStore()
  const initDialogForm: AccountDialogFormState = {
    username: '',
    phone: '',
    enabled: true,
    currentRole: [],
  }
  const dialogState = reactive<DialogState>({
    visible: false,
    type: 'add',
    title: '添加账号',
    formState: cloneDeep(initDialogForm),
    roleList: [],
  })

  onMounted(async () => {
    const { data } = await fetchRoleList({ current: -1, size: 10 })
    dialogState.roleList = data.records
  })
  const fetchRoleListLoading = computed(() =>
    store.getters['global/isOpLoading'](RolesApi.GET_ROLE_LIST)
  )

  watchEffect(async () => {
    if (!dialogState.visible) {
      dialogState.formState = cloneDeep(initDialogForm)
    }
  })

  const openAddUser = async () => {
    dialogState.type = 'add'
    dialogState.title = '添加账号'
    dialogState.visible = true
  }

  const openEditUser = async (row: CommonUserInfo) => {
    dialogState.type = 'edit'
    dialogState.title = '编辑账号'
    dialogState.formState.id = row.id
    dialogState.formState.avatar = row.avatar
    dialogState.formState.mail = row.mail
    dialogState.formState.name = row.name
    dialogState.formState.phone = row.phone
    dialogState.formState.username = row.username
    dialogState.formState.enabled = row.enabled
    const { data } = await fetchAccountRoleList(row.id)
    dialogState.formState.currentRole = data
    dialogState.visible = true
  }
  const fetchAccountRoleListLoading = computed(() =>
    store.getters['global/isOpLoading'](AccountApi.GET_ACCOUNT_ROLE_LIST)
  )

  const resetPassword = async (row: CommonUserInfo | string[]) => {
    let reqData: string[] = []
    if (isArray(row)) {
      reqData = row
    } else {
      reqData = [row.id]
    }
    await resetAccountPassword(reqData)
    message.success('密码重置成功！')
  }
  const resetAccountPasswordLoading = computed(() =>
    store.getters['global/isOpLoading'](AccountApi.RESET_ACCOUNT_PADDWORD)
  )

  const delUser = async (row: CommonUserInfo) => {
    await deleteAccount(row.id)
    message.success('删除成功！')
    await searchApi()
  }
  const deleteAccountLoading = computed(() =>
    store.getters['global/isOpLoading'](AccountApi.DELETE_ACCOUNT)
  )

  const addUser = async () => {
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    const { id, enabled, currentRole, ...resFormState } = dialogState.formState
    // 插入用户
    const insertAccountReqData: InsertAccountReq = {
      ...resFormState,
      clientId: store.state.account.clientId,
    }
    const { data } = await insertAccount(insertAccountReqData)
    return data.id
  }

  const modifyUser = async () => {
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    const { enabled, currentRole, ...resFormState } = dialogState.formState
    // 更新用户信息
    const updateAccountReqData: ModifyAccountReq = {
      id: resFormState.id || '',
      ...resFormState,
    }
    await updateAccount(updateAccountReqData)
    return updateAccountReqData.id
  }

  // 更新用户角色
  const updateUserRole = async (userId: string) => {
    const updateAccountRoleReq: ModifyAccountRoleReq = {
      id: userId,
      roleIds: dialogState.formState.currentRole,
    }
    await updateAccountRole(updateAccountRoleReq)
  }

  const confirmDialog = async () => {
    if (dialogState.type === 'add') {
      await updateUserRole(await addUser())
      message.success('新增用户成功')
    } else if (dialogState.type === 'edit') {
      await updateUserRole(await modifyUser())
      message.success('修改用户成功')
    }
    await searchApi()
    dialogState.visible = false
  }
  const insertAccountLoading = computed(() =>
    store.getters['global/isOpLoading'](AccountApi.INSERT_ACCOUNT)
  )
  const updateAccountLoading = computed(() =>
    store.getters['global/isOpLoading'](AccountApi.UPDATE_ACCOUNT)
  )
  const updateAccountRoleLoading = computed(() =>
    store.getters['global/isOpLoading'](AccountApi.UPDATE_ACCOUNT_ROLE)
  )

  return {
    dialogState,
    confirmDialog,
    openAddUser,
    insertAccountLoading,
    fetchRoleListLoading,
    openEditUser,
    updateAccountLoading,
    delUser,
    updateAccountRoleLoading,
    fetchAccountRoleListLoading,
    deleteAccountLoading,
    resetPassword,
    resetAccountPasswordLoading,
  }
}

export default useModifyUser
